import axios from 'axios'
import {
  Message
} from 'element-ui'
import {
  userLogout,
  refreshToken,
  getAuthToken
} from '@/utils/auth'
import {X_ACCESS_TOKEN, X_ACCESS_APP_ID} from '../config/sysconsts'
import qs from 'qs'
import {debounce} from 'throttle-debounce'

const errorMessage = debounce(500, (message, type = 'error') => {
  Message({
    message: message,
    duration: 1500,
    type: type
  })
})
const Logout = debounce(500, (fullPath) => {
  userLogout(fullPath)
})
const confirmMessage = debounce(1000, (message) => {
  console.log('window.app.$route', window.app.$route)
  if (window.app.$route && window.app.$route.name && window.app.$route.name !== null && window.app.$route.name !== 'login') {
    window.app.$msgBox.delayeOff('提示', message, () => {
      // 删除登录记录
      Logout(window.app.$route.fullPath)
    }, 5, 'warning')
  }
})
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.headers[X_ACCESS_APP_ID] = process.env.APP_ID
let service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 600000 // 请求超时时间
})
// 请求拦截器
service.interceptors.request.use(
  config => {
    // const isNotSetToken = (config.headers['needToken'] && config.headers['needToken'] === false) || false
    // 设置Token
    if (config.url !== '/auth/login') {
      const token = getAuthToken()
      if (token) {
        config.headers[X_ACCESS_TOKEN] = token
      }
      if (config.url.startsWith('/api')) {
        config.url = config.url.replace('/api', '')
      }
    }

    if (config.url.indexOf('undefined') > 0 || config.url.indexOf('null') > 0) {
      console.error('请求参数错误', config.url)
      errorMessage('请求参数错误')
      return
    }
    // 文件上传
    const type = config.headers['Content-Type'] && config.headers['Content-Type'].indexOf('multipart/form-data') !== -1
    if (type !== undefined && !type) {
      config.data = qs.stringify(config.data)
    } else if (config.data === undefined || config.data === null) {
      config.data = {}
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截器
service.interceptors.response.use(
  // JSON响应格式 {"code":XXX错误码,message:XXX消息,data:XXX数据}
  // 错误码：0-成功
  response => {
    const res = response.data
    // console.log('response.status', response.status)
    if (response.headers['Refresh-Token']) {
      // 触发刷新Token
      refreshToken()
    }
    if (response.status === 200 && response.config.responseType === 'blob') {
      // 文件处理
      if (response.status === 200 && response.config.responseType === 'blob') {
        if (response.headers['content-disposition'] || (response.headers['content-type'] && response.headers['content-type'].indexOf('application/pdf') !== -1)) {
          return response
        } else {
          const resultBlob = new Blob([response.data], {type: 'application/json'})
          const fr = new FileReader()
          fr.onload = function () {
            const result = JSON.parse(this.result)
            if (result.message) {
              errorMessage(result.message, result.code === 1 ? 'success' : 'error')
            }
          }
          fr.onerror = function () {
            errorMessage('响应文件错误')
          }
          fr.readAsText(resultBlob)
        }
      }
    } else if (res.code !== 0) {
      if (res.message) {
        errorMessage(res.message)
      }
      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    if (error.response) {
      const response = error.response
      if (response.status === 500) {
        errorMessage('网络错误，请检查您的网络')
      } else if (response.status === 401) {
        confirmMessage(`您的账号登录已失效，请重新登录`)
      } else if (response.data && response.data.message) {
        errorMessage(response.data.message)
      }
    }
    return Promise.reject(error)
  }
)

export default service
